<template>
  <a-drawer v-model:visible="vdata.visible" width="40%" :mask-closable="false" @close="close">
    <template #title>
      <div
        style="
            display: flex;
            justify-content: space-between;
            align-items: center;
          "
      >
        <span>数据匹配</span>
        <!-- <a-button type="link" @click="exportCode(vdata.record)">导出渠道</a-button> -->
      </div>
    </template>
    <a-tabs v-model:activeKey="vdata.singleActiveKey">
      <a-tab-pane :key="1" tab="绑卡消费福分数据匹配" />
      <a-tab-pane :key="2" tab="根据手机号福分数据匹配" />
    </a-tabs>
    <div class="container">
      <a-form
        ref="formRef"
        layout="vertical"
        :model="vdata.saveObject"
        :label-col="{ span: 24 }"
        :wrapper-col="{ span: 24 }"
        class="form"
        :rules="rules"
      >
        <a-row>
          <a-col :span="24">
            <a-form-item name="fileList">
              <template #label>
                <span style="margin-right: 20px">文件上传</span>
                <a-button v-if="vdata.singleActiveKey ==1" type="link" href="https://jdyd-test.oss-cn-hangzhou.aliyuncs.com/henan/template/924bb2c5-1537-41fc-9d2f-f7b4f1bb6d01.xlsx" style="margin: 0;">
                  下载绑卡消费福分数据匹配模板
                </a-button>
                <a-button v-if="vdata.singleActiveKey ==2" type="link" href="https://jdyd-test.oss-cn-hangzhou.aliyuncs.com/henan/template/8813df9e-694f-49ef-9647-c223bca11882.xlsx" style="margin: 0;">
                  下载手机号福分数据匹配模板
                </a-button>
              </template>
              <a-upload-dragger
                v-model:fileList="vdata.saveObject['fileList']"
                :action="vdata['action']"
                :data="vdata.formParams"
                :maxCount="1"
                accept=".xlsx, .xls"
                name="file"
                :beforeUpload="beforeUpload"
                @change="uploadChange"
              >
                <p class="ant-upload-drag-icon">
                  <InboxOutlined />
                </p>
                <p class="ant-upload-text">拖动到此处上传，或<a>点击上传</a></p>
                <p class="ant-upload-hint">
                  <b style="color: #ff4d4f">每次只能上传一个文件，</b>限制文件格式为XLS/XLSX。
                </p>
              </a-upload-dragger>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <!-- 列表展示 -->
    </div>
    <div v-if="vdata.successInfo">匹配成功：<a :href="vdata.successInfo">{{ vdata.successInfo }}</a></div>
  </a-drawer>
</template>
  <script lang="ts" setup>
  import { reactive, getCurrentInstance } from 'vue'
  import request from '@/http/request'
  
  import { req, API_MCHINFO_COMPARE, $getUploadFormParams,API_ACTIVITY_CARDCONSUMPTIONPOINTS,API_ACTIVITY_OTHERPOINTS } from '@/api/manage'
  
  import * as XLSX from 'xlsx'
  const props = defineProps(['callBackFunc'])
  const { $infoBox } = getCurrentInstance()!.appContext.config.globalProperties
  const vdata = reactive({
    visible: false,
    singleActiveKey:1,
    successInfo:'',
    time:'',
    saveObject: {
      fileList: []
    },
    ossFileUrl: '',
    action: '', //上传地址
    formParams: ''
  })
  
  /**
   * 文件上传
   */
  function beforeUpload(file) {
    console.log('file', file)
    // 校验文件大小 不大于20MB
    const isLt20M = file.size / 1024 / 1024 < 20
    if (!isLt20M) {
      $infoBox.message.warn('文件大小不能超过20MB！')
      return false
    }
    // 校验文件格式
    const isExcel = /\.(xlsx|xls)$/.test(file.name)
    if (!isExcel) {
      $infoBox.message.warn('文件格式必须为XLS/XLSX！')
      return false
    }
    return $getUploadFormParams(file, 'upload').then((res) => {
        console.log(res,'上传的文件地址')
      vdata.action = res.formActionUrl // action
      vdata.formParams = res.formParams //表单组件
      vdata.ossFileUrl = res.ossFileUrl
    })
  }
  
  function uploadChange(info) {
    if (info.file.status === 'error') {
      // 上传异常
      vdata.saveObject.fileList = []
      $infoBox.message.error('上传异常,请联系系统管理员')
    }
  
    if (info.file.status === 'done') {
      // 上传成功
    //   判断是哪一种方式上传的
    // request.exportExcel(API_ACTIVITY_CARDCONSUMPTIONPOINTS, { ossFileUrl: vdata.ossFileUrl }, 'POST', '绑卡消费福分数据匹配.xlsx').then(res => {
    //     console.log('res福分', res)
    //   })
    if(vdata.singleActiveKey ==1){
        // 福分
        req.add(API_ACTIVITY_CARDCONSUMPTIONPOINTS, { ossFileUrl: vdata.ossFileUrl }).then(res => {
        console.log('res福分', res)
        // vdata.successInfo = res.successUrl
        // failUrl
        const successUrl = res.successUrl
        const failUrl = res.failUrl
        if(successUrl){
          const link = document.createElement('a')
          link.href = successUrl
          link.download = 'filename.xlsx' // 设置下载文件名
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link)
        }
        if(failUrl){
          setTimeout(() => {
            const link = document.createElement('a')
          link.href = failUrl
          link.download = 'filename.xlsx' // 设置下载文件名
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link)
          }, 200)
        }

        // if(res.data)
        // vdata.time = res.time + '.xlsx'
      })
    }else{
        // 手机号
        req.add(API_ACTIVITY_OTHERPOINTS, { ossFileUrl: vdata.ossFileUrl }).then(res => {
        console.log('res福分', res)
        // vdata.successInfo = res
        // vdata.time = res.time + '.xlsx'
        const successUrl = res.successUrl
        const failUrl = res.failUrl
        if(successUrl){
          const link = document.createElement('a')
          link.href = successUrl
          link.download = 'filename.xlsx' // 设置下载文件名
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link)
        }
        if(failUrl){
          setTimeout(() => {
            const link = document.createElement('a')
          link.href = failUrl
          link.download = 'filename.xlsx' // 设置下载文件名
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link)
          }, 200)
        }
      })

    }

      // req.list(API_MCHINFO_COMPARE,{ossFileUrl:vdata.ossFileUrl}).then(res=>{
      //     console.log(res)
      // })
    }
  }
  
  const close = () => {
    vdata.visible = false
  }
  
  
  // excel表格导出函数数据
  const exportToExcel = (item, name) => {
    // 创建一个工作簿
    const workbook = XLSX.utils.book_new()
  
    // 创建一个工作表
    const worksheet = XLSX.utils.aoa_to_sheet([...item])
  
    // 将工作表添加到工作簿
    XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1')
  
    // 生成Excel文件
    XLSX.writeFile(workbook, `${name}.xlsx`)
  }
  
  // 商户模板下载
  function merchantTemplate() {
    let tempalteInformation = undefined
    let tempalteName
    tempalteName = '商户数据对比模板下载'
    tempalteInformation = [
      ['商户号', '微信间连号', '支付宝间连号'],
  
    ]
    exportToExcel(tempalteInformation, tempalteName)
  }
  
  /**
   * 展开
   */
  async function show(record) {
    vdata.singleActiveKey = 1
    vdata.visible = true
  }
  
  defineExpose({
    show,
  })
  </script>
  <style lang="less"></style>